# -*- coding: utf-8 -*-

import math
import time
from scrapy import log
from snowball_crawler.items import  SnowballRebalancingItem
from snowball_crawler.pipelines import mongodb


class snowballRebalancingPipeline(mongodb.mongodbPipeline):
    """
       save rebalancing data to mongodb
    """

    def process_item(self, item, spider):
         if  isinstance(item, SnowballRebalancingItem):
             his_rebalancing = item['his_rebalancing']
             symbol = item['symbol']
             info = {
                 'symbol': symbol,
                 'last_his_updatetime': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
             }
             for balancing in his_rebalancing:
                 updated_time = time.strftime("%Y-%m-%d %H:%M:%S",
                                              time.localtime(math.trunc(balancing['updated_at'] / 1000)))
                 info.update({ 'his_rebalancing.%s' % balancing['id']: balancing})
          #   info.update({'his_rebalancing': his_rebalancing})
             result = self.db['cubes'].update_one({'symbol': info['symbol']}, {'$set': info}, True)
             log.msg("Item %s updated to MongoDB database %s/rebalance" % (result, self.MONGODB_DB), level=log.DEBUG,
                         spider=spider)

         return item
